﻿using CommonModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace CommonUtils
{
    public class EnumUtil
    {
        /// <summary>
        /// 获取枚举成员的自定义Attribute的一个属性值
        /// </summary>
        /// <param name="e">枚举成员</param>
        /// <returns></returns>
        public static string GetEnumDescription(Type t, object e)
        {

            //获取Type对象的所有字段

            FieldInfo[] ms = t.GetFields();

            //遍历所有字段

            foreach (FieldInfo f in ms)
            {
                if (f.Name != e.ToString())
                {
                    continue;
                }
                if (f.IsDefined(typeof(EnumDisplayNameAttribute), true))
                {
                    return (f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true)[0] as EnumDisplayNameAttribute).DisplayName;
                }
            }
            return e.ToString();
        }

        /// <summary>
        /// Enum转为dictionary ，用于前端展示的转换
        /// </summary>
        /// <param name="enumtype"></param>
        /// <returns></returns>
        public static Dictionary<string, string> EnumToDictionary(Type enumtype)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            foreach (var t in Enum.GetValues(enumtype))
            {
                dic.Add(((int)t).ToString(), GetEnumDescription(enumtype, t));
            }

            return dic.OrderBy(kv => kv.Key).ToDictionary(kv => kv.Key, kv => kv.Value);
        }
        /// <summary>
        /// Enum转list
        /// </summary>
        /// <param name="enumtype"></param>
        /// <returns></returns>
        public static List<Dictionary<string, string>> EnumToList(Type enumtype)
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            foreach (var t in Enum.GetValues(enumtype))
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("value", ((int)t).ToString());
                dic.Add("text", GetEnumDescription(enumtype, t));
                list.Add(dic);
            }
            return list.OrderBy(v => int.Parse(v["value"])).ToList();
        }

    }
}
